package org.sky.util;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author weifx
 * @Title: CamelUtils
 * @ProjectName springboot-platform
 * @Description: TODO{字符驼峰转换}
 * @date 2019/2/26 15:35
 * @Version 1.0
 */
public class CamelUtils {
    private static final char UNDERLINE = '_';

    /**
     * 驼峰格式字符串转换为下划线格式字符串
     * @param param
     * @return
     */
    public static String camelToUnderline(String param) {
        if(StringUtils.isBlank(param)) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    /**
     * 下划线格式字符串转换为驼峰格式字符串2
     * @param param
     * @return
     */
    public static String underlineToCamel(String param) {
        if(StringUtils.isBlank(param)) {
            return "";
        }
        param = param.toLowerCase();
        StringBuilder sb = new StringBuilder(param);
        Matcher mc = Pattern.compile("_").matcher(param);
        int i = 0;
        while (mc.find()) {
            int position = mc.end() - (i++);
            sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 首字母转小写
     * @param param
     * @return
     */
    public static String toLowerCaseFirstChar(String param){
        if(Character.isLowerCase(param.charAt(0))) {
            return param;
        }else {
            return (new StringBuilder()).append(Character.toLowerCase(param.charAt(0))).append(param.substring(1)).toString();
        }
    }

    /**
     * 首字母转大写
     * @param param
     * @return
     */
    public static String toUpperCaseFirstChar(String param){
        if(Character.isUpperCase(param.charAt(0)))
            return param;
        else
            return (new StringBuilder()).append(Character.toUpperCase(param.charAt(0))).append(param.substring(1)).toString();
    }

    /**
     * MapKey 驼峰规则转换
     * @param list
     * @return
     */
    public static List lowerMapKey(List<Map> list){
        List<Map<String,Object>> afterList = new ArrayList<Map<String,Object>>();
        for(Map<String,Object> map:list){
            Map<String, Object> aftermap = new HashMap<String, Object>();
            for(Map.Entry<String,Object> entry: map.entrySet()) {
                String key = underlineToCamel(entry.getKey());
                aftermap.put(key, entry.getValue());
            }
            afterList.add(aftermap);
        }
        return afterList;
    }
}
